package cn.cds.withyou.lib.image.impl;

import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.ViewScaleType;
import com.nostra13.universalimageloader.core.imageaware.NonViewAware;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

public class ResizeImageAware
        extends NonViewAware
{
    protected Reference<View> viewRef;

    public ResizeImageAware(ImageView view, String imageUri, ImageSize imageSize, ViewScaleType scaleType)
    {
        super(imageSize, scaleType);
        this.viewRef = new WeakReference(view);
    }

    public boolean setImageDrawable(Drawable drawable)
    {
        if (Looper.myLooper() == Looper.getMainLooper())
        {
            View view = (View)this.viewRef.get();
            if (view != null)
            {
                setImageDrawableInto(drawable, view);
                return true;
            }
        }
        return false;
    }

    public boolean setImageBitmap(Bitmap bitmap)
    {
        if (Looper.myLooper() == Looper.getMainLooper())
        {
            View view = (View)this.viewRef.get();
            if (view != null)
            {
                setImageBitmapInto(bitmap, view);
                return true;
            }
        }
        return false;
    }

    protected void setImageDrawableInto(Drawable drawable, View view)
    {
        ((ImageView)view).setImageDrawable(drawable);
        if ((drawable instanceof AnimationDrawable)) {
            ((AnimationDrawable)drawable).start();
        }
    }

    protected void setImageBitmapInto(Bitmap bitmap, View view)
    {
        ((ImageView)view).setImageBitmap(bitmap);
    }
}
